package com.starblink.search.result.ui.fragment.post

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.rocketreserver.SearchPostQuery
import com.starblink.rocketreserver.fragment.PostF
import kotlinx.coroutines.launch

internal class PostResultVM : BaseViewModel() {

    var keyWord = ""

    var type : Int? = null

    var pageNo = 1

    val contentList = arrayListOf<PostF>()

    val contentLD = MutableLiveData<List<PostF>>()

    fun loadData() {
        viewModelScope.launch {
            val res = SkGqlClient.skQuery(
                SearchPostQuery(
                    content = keyWord,
                    contentType = if (type == null ) Optional.absent() else type.toString().optional(),
                    pageNo = pageNo,
                    size = PAGE_SIZE.optional(),
                )
            )
            val list = res?.data?.searchPost?.map { it.postF } ?: arrayListOf()

            if (pageNo == 1) {
                contentList.clear()
            }
            contentList.addAll(list)
            contentLD.postValue(list)

            loadHideProgress()
            loadSuccess()
        }

    }

    companion object {

        const val TYPE_VIDEO = 2

        const val TYPE_IMAGE = 1

        const val PAGE_SIZE = 30

    }

}